package com.limao.CacheManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.Hazelcast.Cache;
import com.Hazelcast.CacheFactory;
import com.limao.DBDataClass.CrowdSysPriceDataClass;
import com.limao.DBProvider.CrowdSysPriceProvider;
import com.limao.Tool.CacheClass;
import com.limao.cache.BasicModule;

public class CrowdSysPriceCache  extends BasicModule{

	private CrowdSysPriceProvider provider;
	private static CrowdSysPriceCache instance;

	public static CrowdSysPriceCache getInstance() {
		return instance;
	}

	private Cache<String, CrowdSysPriceDataClass> CrowdSysPriceCache;

	public CrowdSysPriceCache() {
    	super("CrowdSysPriceCache");
    	CrowdSysPriceCache = CacheFactory.createCache("sys_crowd_PriceCache");
		initProvider();
	}
    
    @Override
	public void initialize() {
        super.initialize();
        instance=this;
    }
	
    public void ClearObjectCache()
    {
   		CrowdSysPriceCache.clear();
    } 
    
    
    public List<CrowdSysPriceDataClass> load_PriceList()
    {
    	if(CrowdSysPriceCache.size()==0)
      	{
      		List<CrowdSysPriceDataClass> list=provider.load_PriceList();
        	for(int i=0;i<list.size();i++)
        	{
        		CrowdSysPriceDataClass tmp=list.get(i);
        		CrowdSysPriceCache.put(tmp.priceid, tmp);
        	}
        	return list;
      	}
      	
      	ArrayList<CrowdSysPriceDataClass> list=new ArrayList<CrowdSysPriceDataClass>();
        Set set =CrowdSysPriceCache.keySet();
    	Iterator it=set.iterator();
    	while(it.hasNext()){
     		String s= (String) it.next();
    		list.add(CrowdSysPriceCache.get(s));
    	}
    	//升序
    	Collections.sort(list, new Comparator<CrowdSysPriceDataClass>() {
    		public int compare(CrowdSysPriceDataClass arg0, CrowdSysPriceDataClass arg1) {
    				return ((Float)CacheClass.getFloatValue(arg0.sortvalue)).compareTo(CacheClass.getFloatValue(arg1.sortvalue));
    		}
    	});

    	return list;
    } 
	
	
    public CrowdSysPriceDataClass  load_PriceByPriceid(int priceid)
    {
    	CrowdSysPriceDataClass obj=CrowdSysPriceCache.get(priceid+"");
    	if(obj==null)
    	{
    		obj=provider.load_PriceByPriceid(priceid);
    		if(obj!=null)
    		{
    			CrowdSysPriceCache.put(obj.priceid, obj);
    		}
    	}
    	return obj;
    } 
	
    
  
	//**************************************************************************************************/	
	private void initProvider() {
		if (provider == null) {
			try {
				provider = CrowdSysPriceProvider.getInstance();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	

}
